package stack;

public class ReversePolishNotation {
    public static void main(String[] args) {
//中缀表达式3*（17-15）+18/6的逆波兰表达式如下
        String[] notation = {"3", "17", "15", "-", "*","18", "6","/","+"};
        int result = caculate(notation);
        System.out.println("逆波兰表达式的结果为："+result);
    }
    /**
     * @param notaion 逆波兰表达式的数组表示方式
     * @return 逆波兰表达式的计算结果
     */
    public static int caculate(String[] notaion){
        Stack<Integer> stack = new Stack<>();


        for (int i = 0 ; i < notaion.length ; i ++){
            String s = notaion[i];
            int p1;
            int  p2;
            int res;
            switch (s){
                case "+":
                    p1 = stack.pop();
                    p2 = stack.pop();
                    res = p2 + p1;
                    stack.push(res);
                    break;
                case "-":
                    p1 = stack.pop();
                    p2 = stack.pop();
                    res = p2 - p1;
                    stack.push(res);
                    break;
                case "*":
                    p1 = stack.pop();
                    p2 = stack.pop();
                    res = p2 * p1;
                    stack.push(res);
                    break;
                case "/":
                    p1 = stack.pop();
                    p2 = stack.pop();
                    res = p2 / p1;
                    stack.push(res);
                    break;
                default:
                    stack.push(Integer.parseInt(s));
                    break;
            }
        }
        Integer res = stack.pop();
        return res;
    }

}
